<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/12/28
 * Time: 9:43
 */

namespace app\sales\controller;


use app\api\model\user\Users;
use app\common\model\ApiResponse;
use app\common\model\UserCreditRecord;
use app\sales\lib\AbstractSalesController;

class User extends AbstractSalesController
{
    private $users;
    public function __construct()
    {
        $this->users = new Users();
    }

    /**
     * 用户注册接口
     *
     * @return ApiResponse
     */
    public function register() {
        $form = $this->getAndCheckForm([
            ['mobile', 'require|^1[3-9]\d{9}$', '手机号码不能为空|手机号码格式不正确'], // 手机号码
            ['password','require|length:6,255', '密码不能为空|密码长度不能小于6位'], // 密码
            ['realname','require',], // 密码
            ['gender','require',], // 密码
        ]);

        if ($this->users->query_user_exist($form['mobile'])) {
            ApiResponse::error(ApiResponse::ERR_EXISTS,'您的手机号已经注册，可以直接登录！');
        }

        $userData = [
            'mobile'        => $form['mobile'],
            'realname'      => $form['realname'],
            'gender'        => $form['gender'],
            'password'      => passEncrypt($form['password']),
            'regtime'       => time(),
            'register_from' => Users::REGISTER_FROM_SALES_VIP,
        ];
        $user = Users::create($userData);

        Users::set_user_ability($user->id);
        // 注册送积分
        Users::creditTask($user->id, UserCreditRecord::CHANGE_TYPE_REGISTER);

        $user = Users::get($user->id);
        $data = [
            'uid' => $user->id, // 用户id
            'mobile' => $user->mobile, // 手机号
            'regtime' => $user->regtime, // 注册时间
            'gender' => $user->gender??1, // 性别
        ];
        return ApiResponse::success($data);
    }

}